package org.example.studentvote;

import java.util.Scanner;

public class studentVote {
    public static void main(String[] args) {
        // 初始化候选人
        student[] candidates = {
                new student("张三", 1),
                new student("李四", 2),
                new student("王五", 3),
                new student("赵六", 4)
        };

        // 显示候选人信息
        SeeStudent(candidates);

        Scanner scanner = new Scanner(System.in);
        int vote;

        System.out.println("请输入班长候选人代号（数字0结束）：");
        while (scanner.hasNext()) {
            if (!scanner.hasNextInt()) {
                System.out.println("此选票无效，请输入正确的候选人代号！");
                scanner.next(); // 清除无效输入
                continue;
            }
            vote = scanner.nextInt();
            if (vote == 0) break; // 输入0结束投票
            if (vote >= 1 && vote <= 4) {
                candidates[vote - 1].addVote(); // 投票给相应候选人
            } else {
                System.out.println("此选票无效，请输入正确的候选人代号！");
            }
        }

        // 显示投票结果
        Results(candidates);

        // 确定并显示最终当选者
        student winner = Winner(candidates);
        System.out.println("投票最终结果：" + winner.getName() + "同学，最后以" + winner.getVotes() + "票当选班长！");
    }

    private static void SeeStudent(student[] candidates) {
        for (student candidate : candidates) {
            System.out.println(candidate.getId() + "：" + candidate.getName() + "【0票】");
        }
    }

    private static void Results(student[] candidates) {
        for (student candidate : candidates) {
            System.out.println(candidate.getId() + "：" + candidate.getName() + "【" + candidate.getVotes() + "票】");
        }
    }

    private static student Winner(student[] candidates) {
        student winner = candidates[0];
        for (student candidate : candidates) {
            if (candidate.getVotes() > winner.getVotes()) {
                winner = candidate;
            }
        }
        return winner;
    }
}
